/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package zerocopybuffer_nov26;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;


//I used the following namespace only for writing the final result into a text file
     import java.io.*;
import java.net.SocketAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author Teva
 */
public class ZeroCopyBufferClient {

    /**
     * @param args the command line arguments
     */
    private static long start;
    private static long end;
    private static String Filepath;
    private static boolean Blocking = true; 
    
    public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException 
    {
        int BufferSize = 100512;  
        
        int k;
      
        int j;
        
        writeResult("================================");
        writeResult("NIO Approach Testing");
        writeResult("Configuration Blocking =>" + Blocking);
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd  HH:mm:ss");
        Date date = new Date();
        writeResult("Test Date  " + dateFormat.format(date));
        writeResult("Included: [Prefetching.]");
        writeResult("Buffer Size =>" + BufferSize);
        writeResult("================================");
             int i=0;
            
          for(j=11;j<12;j++) //this loop is used to crawl 7 files
           {
            StringBuilder FP = new StringBuilder("/Users/teva/Desktop/DataFile/File").append(j).append(".txt"); 
            Filepath = FP.toString();
            Prefecthing(Filepath,BufferSize);
             for(k=1;k<2;k++) //this loop is used to change the buffer size
             {
                 for(i=1;i<5;i++)
                 {  
                   writeResult("Iteration No=> " + i + " AND File name is=> File" + j + "Total time =>" + SendFile(Filepath, BufferSize));
                 }
             }
           } 
     }
    
    static long totaltime;
    
    public static long SendFile(String FilePath,int bufferSize)
    {
     
     SocketChannel sc = null;
     FileChannel fc = null;    
     File input = new File(FilePath);     
     try
      {
        System.out.println("Client ZeroCopyBuffer method initiating..."); 
        
        SocketAddress sad = new InetSocketAddress("10.141.11.125",3289);
                
        sc = SocketChannel.open();
        
        sc.connect(sad); 
        
        sc.configureBlocking(Blocking);  
        
        System.out.println("Client channel connected");            
                        
        fc = new FileInputStream(input).getChannel();    
       
        long position = 0;
        
        bufferSize = sc.socket().getSendBufferSize();
        int totalIterations = (int) (fc.size()/bufferSize);
        System.out.println("TOTAL INTERATIONS" + totalIterations);
        int remaining = (int)(fc.size() - (totalIterations * bufferSize));
        
        
        start = System.currentTimeMillis();
           
            for(int i=0;i<totalIterations;i++)
            {
                 position += fc.transferTo(position, bufferSize, sc);
                 //System.out.println("Positions" + position);
            }

            if(remaining > 0)
            {
                position +=fc.transferTo(position, remaining, sc);
            }
       end = System.currentTimeMillis();
       
          totaltime = (int)(end - start);
          System.out.println("Network ZeroCopy Buffer transfer time from client side = "+(end-start)+"ms");
          writeResult("Network ZeroCopy Buffer transfer time from client side = "+(end-start)+"ms");
          sc.close();
          fc.close();  
          return totaltime;
      }
      catch (IOException e) 
      {
            e.printStackTrace();
            return -1;
      }     
    }
    
  public static void writeResult(String Results)
     {
    try {
        FileWriter outFile = new FileWriter("/Users/teva/Desktop/ZeroBufferResult.txt",true);
        PrintWriter out = new PrintWriter(outFile);     
        out.println(Results);        
        out.close();
} 
    catch(IOException e)
    { e.printStackTrace();}
    
     }
  
  public static void Prefecthing(String FilePath,int Buffer) throws FileNotFoundException, IOException 
    {
        
        FileChannel fc1 = null;
        
        fc1 = new FileInputStream(FilePath).getChannel();
        
        ByteBuffer bb = ByteBuffer.allocate(Buffer);
        
        int len=0;
        
        while((len=fc1.read(bb))>=0) 
        {
          bb.clear();
        }
       
    }
     
     
}
